<!--
 * @Author: wei_jt@ecidi.com
 * @Date: 2019-09-26 11:31:26
 * @LastEditors: zhong_m
 * @LastEditTime: 2021-12-28 11:19:25
 * @Description: 角色配置
 -->
<template>
  <div style="min-width: 564px">
    <div id="auth" style="height: 100%">
      <div class="right-container">
        <div style="height: 100%">
          <fks-query-page
            v-loading="loading"
            :data="list"
            :current-page.sync="currentPage"
            :page-sizes="[20, 50, 100]"
            :page-size.sync="pageSize"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total"
            :table-name="LANG.STM_ROLE"
            :border="false"
            @query="getRoles"
            @sort-change="sortHandler"
          >
            <template slot="singleSearch">
              <div class="single-searchBox">
                <fks-input
                  v-model="searchValue"
                  size
                  class="single-searchBox-item"
                  maxlength="50"
                  :placeholder="LANG.SEARCH_PLACEHOLDER"
                  clearable
                  @keyup.native.enter="search"
                  @clear="search"
                >
                  <fks-button
                    slot="append"
                    icon="fks-icon-search"
                    @click="search"
                  />
                </fks-input>
                <fks-button
                  v-permission:1="['role:add']"
                  type="primary"
                  icon="fks-icon-plus"
                  @click="addRole"
                >
                  {{ LANG.ADD }}
                </fks-button>
              </div>
            </template>
            <template>
              <fks-table-column
                type="index"
                align="center"
                label="#"
                width="60"
              />
              <fks-table-column
                :label="LANG.NAME"
                is-link
                prop="name"
                sortable="custom"
                min-width="120"
                header-align="center"
                align="left"
                @link="authView"
              />
              <fks-table-column
                :label="LANG.CODE"
                min-width="120"
                prop="code"
                sortable="custom"
                header-align="center"
                align="left"
              />
              <fks-table-column
                type="wide"
                prop="remark"
                :label="LANG.REMARK"
                header-align="center"
                align="left"
              />
              <fks-table-column
                prop="isGeneral"
                :render-header="roleSelect"
                header-row-class-name="selectRole"
                align="center"
                header-align="center"
                min-width="80"
              >
                <div slot-scope="scope">
                  <span v-if="scope.row.isGeneral">
                    {{ LANG.COMMON }}
                  </span>
                  <span v-if="!scope.row.isGeneral">
                    {{ LANG.PRIVATE }}
                  </span>
                </div>
              </fks-table-column>
              <fks-table-column
                :label="LANG.OPERATION"
                width="200"
                class-name="role-operation"
                align="left"
              >
                <template slot-scope="scope">
                  <fks-tooltip
                    class="item"
                    effect="dark"
                    :content="LANG.VIEW_USERS"
                    placement="top-start"
                  >
                    <fks-button
                      v-if="
                        !(
                          portal.type == portalType[0].code &&
                          scope.row.isGeneral
                        )
                      "
                      v-permission:1="['role:member']"
                      type="text"
                      @click="handleMember(scope.row)"
                    >
                      {{ LANG.MEMBER }}
                    </fks-button>
                  </fks-tooltip>
                  <fks-button
                    v-if="
                      !(
                        scope.row.roleCode === 'superManager' ||
                        (portal.type > portalType[0].code &&
                          scope.row.isGeneral)
                      )
                    "
                    type="text"
                    @click="authEdit(scope.row)"
                  >
                    {{ LANG.AUTH }}
                  </fks-button>
                  <fks-button
                    v-if="
                      !(
                        scope.row.roleCode === 'superManager' ||
                        (portal.type > portalType[0].code &&
                          scope.row.isGeneral)
                      )
                    "
                    v-permission:1="['role:edit']"
                    type="text"
                    @click="handleEdit(scope.row)"
                  >
                    {{ LANG.EDIT }}
                  </fks-button>
                  <fks-button
                    v-if="
                      !(
                        scope.row.roleCode === 'superManager' ||
                        (portal.type > portalType[0].code &&
                          scope.row.isGeneral)
                      )
                    "
                    v-permission:1="['role:delete']"
                    danger-text
                    @click.native="handleDelete(scope.row)"
                  >
                    {{ LANG.DELETE }}
                  </fks-button>
                </template>
              </fks-table-column>
            </template>
          </fks-query-page>
          <role-detail v-if="visible" :visible.sync="visible" :data="node" />
          <role-auth
            v-if="authVisible"
            :visible.sync="authVisible"
            :data="node"
          />
          <authorize-detail :data="node" :visible.sync="memberVisible" />
        </div>
      </div>
    </div>
  </div>
</template>
<script>
import * as Auth from './api'
import RoleDetail from './RoleDetail'
import RoleAuth from './RoleAuth'
import AuthorizeDetail from './Authorize'
import Mix from '@/mixins/module'
import { ENUM } from '@/store/State/stateTypes'
import { AUTH_CONFIG } from '@/store/State/stateTypes'
export default {
  name: 'Role',
  filters: {},
  components: {
    RoleDetail,
    RoleAuth,
    AuthorizeDetail
  },
  mixins: [Mix],
  data() {
    return {
      list: [],
      currentPage: 1,
      pageSize: 20,
      total: 0,
      loading: false,
      keywords: '',
      visible: false,
      authVisible: false,
      memberVisible: false,
      node: {},
      //默认展开的节点数组
      defaultShowNodes: [],
      isGeneral: '',
      types: '',
      portalIds: this.portalId,
      searchValue: '',
      currentType: '',
      sort: '',
      columnName: '',
      deleteFlag: false
    }
  },
  computed: {
    isGradeAuth() {
      return this.$store.state[AUTH_CONFIG].isGradeAuth
    },
    freeInherit() {
      //单继承
      return this.$store.state[AUTH_CONFIG].gradeAuthType == 2
    },
    portalId() {
      if (this.multiPortal) {
        return this.$store.state.portal.id
      }
      return ''
    },
    portal() {
      return this.$store.state.portal
    },
    portalType() {
      return this.$store.state[ENUM].portalType
    },
    multiPortal() {
      return this.$store.getters.multiPortal
    },
    roleType() {
      let data = [
        { name: this.LANG.ALL },
        { name: this.LANG.COMMON },
        { name: this.LANG.PRIVATE }
      ]
      return data
    }
  },
  watch: {
    currentType: {
      handler: function (val) {
        this.handleClick(val)
      }
    },
    roleType: {
      handler: function (nval, oval) {
        oval.forEach((item, index) => {
          if (item.name === this.currentType) {
            this.currentType = nval[index].name
          }
        })
      }
    }
  },
  mounted() {
    this.currentType = this.LANG.ALL
  },
  methods: {
    sortHandler(data) {
      let params = {}
      if (!data.order) {
        this.sort = ''
        this.columnName = ''
      } else {
        this.sort = data.order == 'ascending' ? 'asc' : 'desc'
        this.columnName = data.prop == 'name' ? 'name' : 'code'
      }
      params = {
        types: this.types,
        portalId: this.portalIds,
        pageNo: this.currentPage,
        pageSize: this.pageSize,
        isGeneral: this.isGeneral,
        searchValue: this.searchValue,
        sort: this.sort,
        columnName: this.columnName
      }
      this.getRoleList(params)
    },
    getRoles() {
      this.loading = true
      if (this.multiPortal && this.portalType) {
        if (
          this.portal.type != this.portalType[0].code &&
          (this.isGeneral || this.isGeneral == '')
        ) {
          this.types = this.portal.type
        } else {
          this.types = ''
        }
      } else {
        this.types = ''
      }
      let params = {
        types: this.types,
        portalId: this.portalIds,
        pageNo: this.currentPage,
        pageSize: this.pageSize,
        isGeneral: this.isGeneral,
        searchValue: this.searchValue,
        sort: this.sort,
        columnName: this.columnName
      }
      this.getRoleList(params)
    },
    @permission('role:query')
    getRoleList(params) {
      Auth.getRoles(params)
        .then((res) => {
          if (res.status) {
            //todo true为应用权限类型
            // if (this.isGradeAuth) {
            //   this.list = res.data
            //   this.$store.commit('Auth/SET_ROLES', JSON.stringify(res.data))
            // } else {
            this.list = res.data.list
            this.total = res.data.total
            // }
          } else {
            this.list = []
          }
          this.loading = false
        })
        .catch(() => {
          this.loading = false
        })
    },
    search() {
      this.currentPage = 1
      this.getRoles()
    },
    authView({ row }) {
      this.node = Object.assign({ operate: 'view' }, row)
      this.node.portalId = this.portalId
      this.authVisible = true
    },
    authEdit(row) {
      this.node = Object.assign({ operate: 'edit' }, row)
      this.node.portalId = this.portalId
      this.authVisible = true
    },
    addChild(row) {
      this.node = { operate: 'add', pathId: row.pathId, parentId: row.id }
      this.visible = true
    },
    handleEdit(row) {
      this.node = Object.assign({}, row)
      this.node.operate = 'edit'
      this.node.portalId = this.portalId
      this.node.isGradeAuth = this.isGradeAuth
      this.visible = true
    },
    addRole() {
      this.node = {
        operate: 'add',
        portalId: this.portalId,
        type: this.portal.type,
        isGeneral: false
      }
      this.visible = true
    },
    handleDelete(val) {
      Auth.getRoleUser({
        portalId: this.portalId,
        pageNo: this.currentPage,
        pageSize: this.pageSize,
        roleId: val.id
      }).then((res) => {
        if (res.status && res.data.total > 0) {
          this.$confirm(this.LANG.CONFIRM_TIPS1, this.LANG.TIPS, {
            type: 'warning',
            confirmButtonText: this.LANG.DELETE,
            cancelButtonText: this.LANG.CANCEL,
            deleteMode: true
          }).then(() => {
            this.deleteRole(val.id)
          })
        } else {
          this.$confirm(this.LANG.CONFIRM_TIPS, this.LANG.TIP, {
            type: 'warning',
            confirmButtonText: this.LANG.DELETE,
            cancelButtonText: this.LANG.CANCEL,
            confirmButtonClass: 'fks-button--danger',
            deleteMode: true
          }).then(() => {
            this.deleteRole(val.id)
          })
        }
      })
    },
    deleteRole(val) {
      Auth.deleteRole(val).then((res) => {
        if (res.status) {
          this.$message({
            type: 'success',
            message: this.LANG.DELETE_SUCCESS
          })
          this.currentPage = 1
          this.getRoles()
        }
      })
    },
    handleMember(row) {
      this.node = Object.assign({}, row)
      this.memberVisible = true
    },
    handleClick(val) {
      if (val == this.LANG.COMMON) {
        this.portalIds = this.portalId
        this.isGeneral = true
      } else if (val == this.LANG.PRIVATE) {
        this.portalIds = this.portalId
        this.isGeneral = false
      } else {
        this.isGeneral = ''
        this.portalIds = this.portalId
      }
      this.getRoles()
    },
    roleSelect(h, { column, $index }) {
      // 给表格添加包裹的div
      return h('div', {}, [
        // 添加el-select 标签
        h(
          'fks-select',
          {
            on: {
              input: (value) => {
                this.currentType = value
              }
            },
            props: {
              value: this.currentType, // 给el-select 设置值（也是相当于v-model）
              size: 'small',
              class: 'selectRole',
              style: {
                height: '25px',
                width: '110px',
                paddingLeft: '0px',
                paddingRight: '0px'
              }
            }
          },
          [
            //给当前 el-select 设置 el-option
            this.roleType.map((item) => {
              return h('fks-option', {
                props: {
                  value: item.name,
                  label: item.name
                }
              })
            })
          ]
        )
      ])
    }
  }
}
</script>
<style rel="stylesheet/scss" lang="scss" scoped>
.right-container {
  position: relative;
  display: inline-block;
  width: 100%;
  height: 100%;
  overflow-x: auto;
  vertical-align: top;
  white-space: nowrap;
}

::v-deep .fks-table th > .cell .fks-input--small .fks-input__inner {
  border: none;
  text-align: center;
  background-color: transparent;
}

::v-deep .fks-select .fks-input .fks-select__caret {
  margin-top: -0.5px;
}

::v-deep .fks-table .fks-input--suffix .fks-input__inner {
  padding-left: 30px !important;
}

.page-box {
  position: absolute;
  z-index: 50;
  bottom: 0;
  left: 0;
  right: 35px;
  background: #fff;

  > .fks-pagination {
    display: flex;
    justify-content: flex-end;
    margin-bottom: 10px;
  }
}
</style>